<?php

  require 'php_monetdb.php';

  // Parameter validation
  if ( !isset($_GET['lat']) || !isset($_GET['long']) )
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die("lat/long parameters needed.");
  }

  $long = stripslashes($_GET['long']);
  $lat = stripslashes($_GET['lat']);

  if (!is_numeric($long) || !is_numeric($lat))
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die("lat/long parameters must be numeric values.");
  }

  // Generate Query
  $db = monetdb_pconnect('sql', 'localhost', 50000, 'monetdb','monetdb', 'nutsgeo');  

  if (!$db)
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die('Failed to connect to MonetDB.');
  }

  $sql = "SELECT r.uri FROM regions r WHERE within('POINT(".$long." ".$lat.")',r.shape) = true";

  $res = monetdb_query($sql);

  if (!$res)
  {
    header('HTTP/1.1 500 Internal Server Error');
    header('Content-type: text/html');
    die('Failed to query MonetDB.');
  }
  monetdb_disconnect($db);

  header('Content-type: application/rdf+xml; charset=utf-8');
  // Echo XML header as a string, so it is not treated as an opening PHP tag.
  echo '<?xml version="1.0" encoding="utf-8"?>';
?>

<rdf:RDF 
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" 
  xmlns:spatial="http://geovocab.org/spatial#"
  xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">

  <rdf:Description rdf:about="">
    <rdfs:comment>Source: NUTS Linked Data Services (http://nuts.geovocab.org/).</rdfs:comment>
  </rdf:Description>

  <rdf:Description rdf:ID="point">
    <geo:lat rdf:datatype="http://www.w3.org/2001/XMLSchema#float"><?php echo $lat; ?></geo:lat>
    <geo:long rdf:datatype="http://www.w3.org/2001/XMLSchema#float"><?php echo $long; ?></geo:long>
  <?php while ( $row = monetdb_fetch_assoc($res) ): ?>
    <spatial:PP rdf:resource="<?php echo $row['uri']; ?>"/>
  <?php endwhile; ?>
  </rdf:Description>
  
</rdf:RDF>
